package com.incar.chuxing.api;

import android.content.Intent;

import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.activity.personal.LoginActivity;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.utils.Logger;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * Created by michaelpi on 2018/1/2.
 */

public class RxApiStore {
    private static RxApiStore instance = null;
    private static Retrofit retrofit;

    private RxApiStore() {
    }

    public static RxApiStore getInstance() {
        if (instance == null) {
            synchronized (RxApiStore.class) {
                if (instance == null) {
                    instance = new RxApiStore();
                }
            }
        }
        return instance;
    }

    /**
     * @return
     */
    public RxApiService getApiService(String baseUrl) {
        return getRetrofit(baseUrl, 120).create(RxApiService.class);
    }

    public RxApiService getApiService(String baseUrl, int timeout) {
        return getRetrofit(baseUrl, timeout).create(RxApiService.class);
    }


    private Retrofit getRetrofit(String baseUrl, int timeout) {
        //配置okHttp
        OkHttpClient.Builder builder = new OkHttpClient
                .Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS);


        //已登录
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder();

            Map<String, String> requestMap = ((MyApplication) MyApplication.getInstance()).getRequestHeaderMap();
            for (String mapKey : requestMap.keySet()) {
                if (requestMap.get(mapKey) != null) {
                    requestBuilder.header(mapKey, requestMap.get(mapKey));
                }
            }
            return chain.proceed(requestBuilder.build());
        });

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> Logger.d("apiMsg", message));
        if (BuildConfig.DEBUG) {  //debug模式
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(MyApplication.chuckInterceptor);
        } else {  //release模式
            logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        }
        builder.addInterceptor(logging);
        builder.addInterceptor(new HttpCodeInterceptor());
        //配置Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        return retrofit;
    }

    public class HttpCodeInterceptor implements Interceptor {
        public static final int HTTP_CODE_LOG_OUT = 401;//Token验证失效

        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            if (response.code() == HTTP_CODE_LOG_OUT) {
                Logger.d("退出登录", "Http退出登录");
                //ToastUtils.makeText(MyApplication.getInstance(), "请重新登录", ToastUtils.LENGTH_SHORT).show();
                Intent intent = new Intent(MyApplication.getInstance(), LoginActivity.class);
                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                MyApplication.getInstance().startActivity(intent);
            }
            return response;
        }

    }
}
